package com.powernode.bank.service.Impl;

import com.powernode.bank.dao.AccountDao;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("accountService")
@Transactional
public class AccountServiceImpl implements AccountService {
    // 逻辑层
    @Resource(name = "accountDao")
    private AccountDao accountDao;

    // 转账业务
    @Override
    public void transfer(String fromActNo, String toActNo, Double balance) {
        // 第一步：开启事务

        // 第二步：执行核心业务逻辑
        // 判断余额是否充足
        Account fromAccount = accountDao.selectByAct(fromActNo);
        Double money = fromAccount.getBalance();
        if (money < balance) {
            throw new RuntimeException("余额不足");
        }

        // 余额充足，修改内存信息
        Account toAccount = accountDao.selectByAct(toActNo);
        fromAccount.setBalance(fromAccount.getBalance() - balance);
        toAccount.setBalance(toAccount.getBalance() + balance);

        // 修改数据库信息
        int count = accountDao.update(fromAccount);

        // 模拟异常
        /*String s = null;
        s.toString();*/

        count += accountDao.update(toAccount);

        if (count != 2) {
            throw new RuntimeException("转账失败，请联系客服");
        }

        // 第三步：提交事务

        // 第四步：遇到异常回滚
    }
}
